"""
关注模型
映射数据库user_follow表
"""
from sqlalchemy import Column, Integer, DateTime, ForeignKey, Index
from sqlalchemy.orm import relationship
from datetime import datetime

from app.extensions import db


class Follow(db.Model):
    """
    关注模型类
    对应数据库中的user_follow表
    注意：此类不继承BaseModel，因为它只有created_at字段，没有updated_at
    """
    
    __tablename__ = "user_follow"
    
    follower_id = Column(
        Integer, 
        ForeignKey('users.id', ondelete='CASCADE', onupdate='CASCADE'), 
        nullable=False,
        primary_key=True,
        comment='关注者ID'
    )
    
    followed_id = Column(
        Integer, 
        ForeignKey('users.id', ondelete='CASCADE', onupdate='CASCADE'), 
        nullable=False,
        primary_key=True,
        comment='被关注者ID'
    )
    
    created_at = Column(
        DateTime, 
        nullable=False, 
        default=datetime.utcnow,
        comment='关注时间'
    )
    
    # 关系定义
    # 关注者（主动关注的人）
    follower = relationship(
        'User', 
        foreign_keys=[follower_id],
        backref='following'  # 用户的关注列表
    )
    
    # 被关注者（被别人关注的人）
    followed = relationship(
        'User', 
        foreign_keys=[followed_id],
        backref='followers'  # 用户的粉丝列表
    )
    
    # 索引
    __table_args__ = (
        # 优化查询性能的索引
        Index('idx_follower_id', 'follower_id'),
        Index('idx_followed_id', 'followed_id'),
    )